package com.tju.resource.business.sys;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tju.resource.common.GlobalCall;
import com.tju.resource.common.ServiceException;
import com.tju.resource.mapper.SysVersionsMapper;
import com.tju.resource.model.SysVersions;
import com.tju.resource.result.Result;
import com.tju.resource.result.ResultEnum;
import com.tju.resource.result.ResultUtil;
import com.tju.resource.tool.tool.ChineseExceptionUtils;
import com.tju.resource.tool.tool.ClientParameters;
import com.tju.resource.tool.enum_utils.SizeConverter.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Optional;


/**
 * 版本业务实现
 *
 * @Author CLS
 * @Date 2022/3/29 14:18
 */
@Slf4j
@Service
public class SysVersionsServiceImpl implements SysVersionsService {


    @Autowired
    private ChineseExceptionUtils zh_ch;

    @Autowired
    private SysVersionsMapper versionsMapper;

    /**
     * 查询当前是否是最新版本
     *
     * @param parameters
     * @return
     */
    @Override
    public Result<Object> getUpdInformation(ClientParameters parameters) {
        try {
            if (!parameters.getFtu().equals("move"))
                throw new ServiceException(zh_ch.MissingParameters);
            QueryWrapper<SysVersions> wrapper = new QueryWrapper<>();
            wrapper.eq("version_code", parameters.getFtu());
            wrapper.eq("current", 1);
            SysVersions versions = versionsMapper.selectOne(wrapper);
            return Optional.ofNullable(versions)
                    .filter(v -> !parameters.getVersionNumber().equals(v.getVersionMark()))
                    .map(v -> ResultUtil.success(ResultEnum.SUCCESS, v))
                    .orElseThrow(() -> new ServiceException(zh_ch.TheLatestVersion));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 获取最新版app
     *
     * @return
     */
    @Override
    public void download(HttpServletResponse response) {
        try {
            QueryWrapper<SysVersions> wrapper = new QueryWrapper<>();
            wrapper.eq("version_code", "move");
            wrapper.eq("current", 1);
            SysVersions versions = versionsMapper.selectOne(wrapper);
            if (versions != null) {
                // path是指想要下载的文件的路径
                File file = new File(GlobalCall.AppPath + "ten_tian_mes_" + versions.getVersionMark() + ".apk");
                //判断文件是否存在
                if (file.isFile() && file.exists()) {
                    // 获取文件名
                    String filename = file.getName();
                    byte[] buffer = FileUtil.readBytes(file);
                    // 清空response
                    response.reset();
                    // 设置response的Header
                    response.setCharacterEncoding("UTF-8");
                    response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8));
                    // 告知浏览器文件的大小
                    response.addHeader("Content-Length", "" + file.length());
                    response.addHeader("Content_length", "" + file.length());
                    response.addHeader("Content_name", filename);
                    // 告知浏览器文件的大小
                    response.addHeader("Content_size", "" + transverter.BTrim.convert(file.length()));
                    response.setContentType("multipart/form-data");
                    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                    outputStream.write(buffer);
                    outputStream.flush();
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ServiceException(e.getMessage());
        }
    }
}
